package com.info.zhiduoduo.weixin.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.crowdsource.CrowdsourceRegfromType;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.constants.maker.MakerType;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.common.AuthService;
import com.info.zhiduoduo.core.vo.auth.UserAuthVO;
import com.info.zhiduoduo.repository.dto.partner.PartnerInfoDto;
import com.info.zhiduoduo.repository.dto.weixin.WxLoginDto;
import com.info.zhiduoduo.repository.dto.weixin.WxUserStateDto;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.crowdsource.Crowdsource;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceAccount;
import com.info.zhiduoduo.repository.entity.maker.Maker;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.partner.Partner;
import com.info.zhiduoduo.repository.entity.partner.PartnerAccount;
import com.info.zhiduoduo.repository.entity.weixin.WxOpenid;
import com.info.zhiduoduo.repository.mapper.company.CompanyMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerAccountMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
import com.info.zhiduoduo.weixin.formbean.weixin.WxCodeFormBean;
import com.info.zhiduoduo.weixin.vo.MakerVo;
import com.info.zhiduoduo.weixin.vo.WxUserInfo;
import com.info.zhiduoduo.wxsdk.WxApiService;
import com.info.zhiduoduo.wxsdk.config.WxCrowdsourceConfig;
import com.info.zhiduoduo.wxsdk.config.WxPartnerConfig;
import com.info.zhiduoduo.wxsdk.config.WxTaxerConfig;
import com.info.zhiduoduo.wxsdk.domain.app.WxAuthorizeAccessToken;
import com.info.zhiduoduo.wxsdk.domain.app.WxAuthorizeUserInfo;
import com.info.zhiduoduo.wxsdk.domain.app.WxNormalAccessToken;
import com.info.zhiduoduo.wxsdk.domain.app.WxShareSignature;
import com.info.zhiduoduo.wxsdk.domain.app.WxTempleteMessage;
import com.info.zhiduoduo.wxsdk.domain.app.WxUserBaseInfo;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class WxService {

	@Autowired
	WxApiService wxApiService;
	@Autowired
	AuthService authService;

	@Autowired
	WxPartnerConfig wxPartnerConfig;

	@Autowired
	WxCrowdsourceConfig wxCrowdsourceConfig;

	@Autowired
	WxTaxerConfig wxTaxerConfig;

	@Resource
	MakerMapper makerMapper;
	@Resource
	MakerStudioMapper makerStudioMapper;

	@Resource
	CompanyMapper companyMapper;

	@Resource
	PartnerMapper partnerMapper;

	@Resource
	PartnerAccountMapper partnerAccountMapper;

	@Autowired
	CrowdsourceAccountMapper crowdsourceAccountMapper;

	/**
	 公众号：微信网页授权时获取用户信息
	 <p>
	 flag 0:进入公众号直接进入首页,可以直接获取用户信息
	 1:点分享进入页面,需要通过网络授权code获取用户信息
	 ApiURL
	 identityType  1创客 2企业 3合伙人

	 @param formBean
	 @return
	 */
	public SmartResult wxWebAuthorize(BaseSimpleFormBean<WxCodeFormBean> formBean) {
		SmartResult smartResult = new SmartResult();
		if (formBean == null || formBean.getReqdata() == null || StringUtil.isEmpty(formBean.getReqdata().getCode())) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int identityType = formBean.getIdtype();
		WxCodeFormBean wxCodeFormBean = formBean.getReqdata();
		int flag = wxCodeFormBean.getFlag();
		String code = wxCodeFormBean.getCode();

		WxAuthorizeAccessToken authorizeAccessToken;
		if (UserType.MAKER == identityType || UserType.COMPANY == identityType) {
			authorizeAccessToken = wxApiService.getAuthorizeAccessToken(code);
		} else if (UserType.PARTNER == identityType) {
			authorizeAccessToken = wxApiService.getAuthorizeAccessToken(code, wxPartnerConfig.getAppid(), wxPartnerConfig.getSecret());
		} else if (UserType.CROWDSOURCE == identityType || UserType.MAKER_CROWDSOURCE == identityType) {
			authorizeAccessToken = wxApiService.getAuthorizeAccessToken(code, wxCrowdsourceConfig.getAppid(),
					wxCrowdsourceConfig.getSecret());
		} else if (UserType.TAXER == identityType) {
			authorizeAccessToken = wxApiService.getAuthorizeAccessToken(code, wxTaxerConfig.getAppid(), wxTaxerConfig.getSecret());
		} else {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		if (authorizeAccessToken == null) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		String openid = authorizeAccessToken.getOpenid();
		String authAccessToken = authorizeAccessToken.getAccess_token();

		if (StringUtil.isEmpty(openid) || StringUtil.isEmpty(authAccessToken)) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		if (UserType.MAKER == identityType || UserType.MAKER_CROWDSOURCE == identityType) {
			//查看是否存在创客
			Maker maker = makerMapper.getUserByOpenid(openid);

			if (null == maker) {
				maker = new Maker();
				maker.setOpenid(openid);

				WxUserInfo wxUserInfo = getWxUserInfo(flag, openid, authAccessToken);
				if (null != wxUserInfo) {
					maker.setAvatar(wxUserInfo.getHeadimgurl());
					maker.setUnionid(wxUserInfo.getUnionid());
					maker.setSex(wxUserInfo.getSex());
					maker.setNickname(wxUserInfo.getNickname());
					maker.setRegfrom(1);
					if (UserType.MAKER == identityType) {
						maker.setMakerType(MakerType.INTELL);
					} else {
						maker.setMakerType(MakerType.CROWDSOURCE);
					}
					maker.setState(1);
				}

				maker.insert();

				smartResult.setObject(maker);
				smartResult.setStateMsg(StatusMsg.StatusMsg_111);

			} else {
				if (StringUtil.isEmpty(maker.getPhone())) {
					smartResult.setStateMsg(StatusMsg.StatusMsg_111);
				}
				MakerVo makerVo = new MakerVo();
				BeanUtils.copyProperties(maker, makerVo);
				//返回工作室状态
				if (maker.getAuthState() == 5) {
					MakerStudio makerStudio = new MakerStudio().selectById(maker.getUserid());
					makerVo.setStudioState(makerStudio.getState());
				}
				smartResult.setObject(makerVo);

			}
			authService.loginSuccess(UserAuthVO.of(maker.getUserid(), identityType, new Date()));
			return smartResult;

		} else if (UserType.COMPANY == identityType) {
			//查看是否存在企业
			Company company = companyMapper.getCompanyByOpenid(openid);
			if (null == company) {
				company = new Company();
				company.setOpenid(openid);

				WxUserInfo wxUserInfo = getWxUserInfo(flag, openid, authAccessToken);
				if (null != wxUserInfo) {
					company.setAvatar(wxUserInfo.getHeadimgurl());
					company.setUnionid(wxUserInfo.getUnionid());
					company.setSex(wxUserInfo.getSex());
					company.setNickname(wxUserInfo.getNickname());
					company.setRegfrom(1);
					company.setState(0);
				}

				company.insert();

				smartResult.setObject(company);
				smartResult.setStateMsg(StatusMsg.StatusMsg_110);
			} else {
				smartResult.setObject(company);

				//已存在compid；还没手机注册
				if (StringUtil.isEmpty(company.getRegphone())) {
					smartResult.setStateMsg(StatusMsg.StatusMsg_110);
				}
			}
			authService.loginSuccess(UserAuthVO.of(company.getCompid(), UserType.COMPANY, new Date()));
			return smartResult;
		} else if (UserType.PARTNER == identityType) {
			//查看是否存在合伙人
			Partner partner = partnerMapper.getPartnerByOpenid(openid);
			if (null == partner) {
				partner = new Partner();
				partner.setOpenid(openid);

				WxUserInfo wxUserInfo = getWxUserInfo(flag, openid, authAccessToken, wxPartnerConfig.getAppid(),
						wxPartnerConfig.getSecret());
				if (null != wxUserInfo) {
					partner.setAvatar(wxUserInfo.getHeadimgurl());
					partner.setUnionid(wxUserInfo.getUnionid());
					partner.setNickname(wxUserInfo.getNickname());
					partner.setSex(wxUserInfo.getSex());
					partner.setRegfrom(1);
					partner.setState(1);
				}
				partner.insert();
				PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
				partnerInfoDto.setWhetherSetPaymentPwd(false);
				partnerInfoDto.setPartner(partner);
				smartResult.setObject(partnerInfoDto);
				smartResult.setStateMsg(StatusMsg.StatusMsg_121);
			} else {
				PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
				PartnerAccount partnerAccount = partnerAccountMapper.getPartnerAccountByPartnerId(partner.getPartnerid());
				if (null != partnerAccount) {
					if (StringUtil.isNotEmpty(partnerAccount.getPayPassword())) {
						partnerInfoDto.setWhetherSetPaymentPwd(true);
					} else {
						partnerInfoDto.setWhetherSetPaymentPwd(false);
					}
				} else {
					partnerInfoDto.setWhetherSetPaymentPwd(false);
				}
				partnerInfoDto.setPartner(partner);
				smartResult.setObject(partnerInfoDto);
				//已存在compid；还没手机注册
				if (StringUtil.isEmpty(partner.getPhone())) {
					smartResult.setStateMsg(StatusMsg.StatusMsg_121);
				}
			}
			authService.loginSuccess(UserAuthVO.of(partner.getPartnerid(), UserType.PARTNER, new Date()));
			return smartResult;
		} else if (UserType.CROWDSOURCE == identityType) {
			//查看是否存在众包自然人
			Crowdsource crowdsource = new Crowdsource().selectOne(Condition.create().eq("openid", openid));

			if (null == crowdsource) {
				crowdsource = new Crowdsource();
				crowdsource.setOpenid(openid);

				WxUserInfo wxUserInfo = getWxUserInfo(flag, openid, authAccessToken, wxCrowdsourceConfig.getAppid(),
						wxCrowdsourceConfig.getSecret());

				if (null != wxUserInfo) {
					crowdsource.setAvatar(wxUserInfo.getHeadimgurl());
					crowdsource.setUnionid(wxUserInfo.getUnionid());
					crowdsource.setSex(wxUserInfo.getSex());
					crowdsource.setNickname(wxUserInfo.getNickname());
					crowdsource.setRegfrom(CrowdsourceRegfromType.WEICHAT);
					crowdsource.setState(1);
				}

				crowdsource.insert();

				smartResult.setObject(crowdsource);
				smartResult.setStateMsg(StatusMsg.StatusMsg_605);
			} else {
				CrowdsourceAccount crowdsourceAccount = new CrowdsourceAccount().selectOne(
						Condition.create().eq("crowdsourceid", crowdsource.getCrowdsourceid()));
				if (crowdsourceAccount != null) {
					crowdsource.setRealnameAuth(crowdsourceAccount.getRealnameAuth());
				}
				smartResult.setObject(crowdsource);

				if (StringUtil.isEmpty(crowdsource.getPhone())) {
					smartResult.setStateMsg(StatusMsg.StatusMsg_605);
				}
			}
			authService.loginSuccess(UserAuthVO.of(crowdsource.getCrowdsourceid(), UserType.CROWDSOURCE, new Date()));
			return smartResult;
		} else if (UserType.TAXER == identityType) {
			//查看是否存在创客
			Maker maker = makerMapper.getUserByTaxerOpenid(openid);

			if (null == maker) {
				maker = new Maker();
				maker.setTaxerOpenid(openid);

				WxUserInfo wxUserInfo = getWxUserInfo(flag, openid, authAccessToken);
				if (null != wxUserInfo) {
					maker.setAvatar(wxUserInfo.getHeadimgurl());
					maker.setUnionid(wxUserInfo.getUnionid());
					maker.setSex(wxUserInfo.getSex());
					maker.setNickname(wxUserInfo.getNickname());
					maker.setRegfrom(1);
					maker.setMakerType(MakerType.TAXER);
					maker.setState(1);
				}

				maker.insert();

				smartResult.setObject(maker);
				smartResult.setStateMsg(StatusMsg.StatusMsg_111);
			} else {
				smartResult.setObject(maker);

				if (StringUtil.isEmpty(maker.getPhone())) {
					smartResult.setStateMsg(StatusMsg.StatusMsg_111);
				}
			}
			authService.loginSuccess(UserAuthVO.of(maker.getUserid(), UserType.TAXER, new Date()));
			return smartResult;
		} else {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
	}

	public void wxClickHomePage(HttpServletRequest request, HttpServletResponse response) {
		/*
		state=type:2,teamid:29
		 格式解析:
		 type:1 进入主页  2:跳分享页面
		 teamid:29 当type=2时才传的参数,表示分享页面
		 */
		String state = request.getParameter("state");
		String code = request.getParameter("ApiURL");
		LogUtil.info("state === " + state + " , ApiURL === " + code);

		WxAuthorizeAccessToken authorizeAccessToken = wxApiService.getAuthorizeAccessToken(code);
		String openid = authorizeAccessToken.getOpenid();
		String accessToken = authorizeAccessToken.getAccess_token();
		int userid = 0;
		if (!StringUtils.isEmpty(openid)) {
			WxOpenid wxOpenid = new WxOpenid().selectOne(Condition.create().eq("openid", openid));

			if (wxOpenid == null) {

				wxOpenid = new WxOpenid();
				wxOpenid.setOpenid(openid);
				wxOpenid.insert();

			} else {
				//已经存在
				userid = wxOpenid.getId();
			}
		}
		//重定向,根据state参数,跳转不同的url, state=type:2,teamid:29
		String toUrl = "";
		Map<String, String> params = parseState(state);
		LogUtil.info("state 解析 : " + params.toString());
		int type = StringUtil.toInt(params.get("type"));
		if (type == 0) {
			//直接跳主页
			toUrl = "http://pagedemo.info666.com/msnew/#/index?userid=" + userid;
		} else if (type == 1) {
			//分享进入主页
			toUrl = "http://pagedemo.info666.com/msnew/#/index?userid=" + userid;
		} else if (type == 2) {
			//分享,解析state后面的参数
			toUrl = "http://pagedemo.info666.com/msnew/#/gpShare?userid=" + userid + "&teamid=" + params.get("teamid");
		}
		LogUtil.info(toUrl);
		try {
			response.sendRedirect(toUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}

		//保存用户信息
		Maker maker = new Maker().selectById(userid);
		if (maker != null && StringUtils.isEmpty(maker.getNickname())) {
			if (type == 0) {
				//				WxUserBaseInfo wxUserInfo = wxService.getWxUserInfo(openid);
				WxUserBaseInfo wxUserInfo = wxApiService.getWxUserInfo(openid);
				if (wxUserInfo != null) {
					String nickname = wxUserInfo.getNickname();
					String headimgurl = wxUserInfo.getHeadimgurl();
					int sex = wxUserInfo.getSex();
					//user.setWechatName(nickname);
					//user.setHeadimgurl(headimgurl);
					maker.setSex(sex);
					maker.updateById();
				}
			} else if (type == 1 || type == 2) {
				//				WxAuthorizeUserInfo authorizeUserInfo = wxService.getAuthorizeUserInfo(accessToken, openid);
				WxAuthorizeUserInfo authorizeUserInfo = wxApiService.getAuthorizeUserInfo(accessToken, openid);
				if (authorizeUserInfo != null) {
					String nickname = authorizeUserInfo.getNickname();
					String headimgurl = authorizeUserInfo.getHeadimgurl();
					int sex = StringUtil.toInt(authorizeUserInfo.getSex());
					//user.setWechatName(nickname);
					//user.setHeadimgurl(headimgurl);
					maker.setSex(sex);
					maker.updateById();
				}
			}
		}
	}

	/**
	 解析如下格式 state=type:2,teamid:29

	 @param state
	 @return
	 */
	public Map<String, String> parseState(String state) {
		Map<String, Object> result = new HashMap<>();
		String[] params = state.split(",");
		return Stream.of(params).collect(HashMap::new, (r, p) -> {
			String[] kv = p.split(":");
			r.put(kv[0], kv[1]);
		}, HashMap::putAll);
	}

	/**
	 获取微信用户的信息

	 @param flag
	 @return
	 */
	private WxUserInfo getWxUserInfo(int flag, String openid, String accessToken) {
		WxUserInfo wxUserInfo = new WxUserInfo();
		if (flag == 0) {
			WxUserBaseInfo wxUserBaseInfo = wxApiService.getWxUserInfo(openid);
			if (null != wxUserBaseInfo) {
				wxUserInfo.setOpenid(wxUserBaseInfo.getOpenid());
				wxUserInfo.setUnionid(wxUserBaseInfo.getUnionid());
				wxUserInfo.setNickname(wxUserBaseInfo.getNickname());
				wxUserInfo.setHeadimgurl(wxUserInfo.getHeadimgurl());
				wxUserInfo.setSex(wxUserInfo.getSex());
			}
		} else {
			WxAuthorizeUserInfo authorizeUserInfo = wxApiService.getAuthorizeUserInfo(accessToken, openid);
			if (authorizeUserInfo != null) {
				wxUserInfo.setOpenid(authorizeUserInfo.getOpenid());
				wxUserInfo.setUnionid(authorizeUserInfo.getUnionid());
				wxUserInfo.setNickname(authorizeUserInfo.getNickname());
				wxUserInfo.setHeadimgurl(authorizeUserInfo.getHeadimgurl());
				wxUserInfo.setSex(StringUtil.toInt(authorizeUserInfo.getSex()));
			}
		}

		return wxUserInfo;
	}

	/**
	 获取微信用户的信息

	 @param flag
	 @return
	 */
	private WxUserInfo getWxUserInfo(int flag, String openid, String accessToken, String appid, String secret) {
		WxUserInfo wxUserInfo = new WxUserInfo();
		if (flag == 0) {
			WxUserBaseInfo wxUserBaseInfo = wxApiService.getWxUserInfo(openid, appid, secret);
			if (null != wxUserBaseInfo) {
				wxUserInfo.setOpenid(wxUserBaseInfo.getOpenid());
				wxUserInfo.setUnionid(wxUserBaseInfo.getUnionid());
				wxUserInfo.setNickname(wxUserBaseInfo.getNickname());
				wxUserInfo.setHeadimgurl(wxUserInfo.getHeadimgurl());
				wxUserInfo.setSex(wxUserInfo.getSex());
			}
		} else {
			WxAuthorizeUserInfo authorizeUserInfo = wxApiService.getAuthorizeUserInfo(accessToken, openid);
			if (authorizeUserInfo != null) {
				wxUserInfo.setOpenid(authorizeUserInfo.getOpenid());
				wxUserInfo.setUnionid(authorizeUserInfo.getUnionid());
				wxUserInfo.setNickname(authorizeUserInfo.getNickname());
				wxUserInfo.setHeadimgurl(authorizeUserInfo.getHeadimgurl());
				wxUserInfo.setSex(StringUtil.toInt(authorizeUserInfo.getSex()));
			}
		}

		return wxUserInfo;
	}

	public SmartResult wxShare(BaseSimpleFormBean<String> formBean) {
		SmartResult smartResult = new SmartResult();

		if (UserType.PARTNER == formBean.getIdtype()) {
			WxShareSignature shareSignature = wxApiService.getShareSignature(formBean.getReqdata(), wxPartnerConfig.getAppid(),
					wxPartnerConfig.getSecret());
			smartResult.setObject(shareSignature);
		} else {
			WxShareSignature shareSignature = wxApiService.getShareSignature(formBean.getReqdata());
			smartResult.setObject(shareSignature);
		}

		return smartResult;
	}

	public SmartResult sendMessage(BaseSimpleFormBean formBean) {
		SmartResult smartResult = new SmartResult();
		int userid = formBean.getUserid();
		WxOpenid wxOpenid = new WxOpenid().selectOne(Condition.create().eq("userid", userid));
		if (wxOpenid == null) {
			smartResult.setState(StatusMsg.StatusMsg_103.getState());
			return smartResult;
		}
		String openid = wxOpenid.getOpenid();

		//		WxTempleteMessage message = new WxTempleteMessage();
		WxTempleteMessage message = new WxTempleteMessage();
		message.setTouser(openid);
		message.setTemplate_id("wzflYsvNWIC2j-Gv5A4xLcTkfLXhoPOEE4GfXJTOTWg");
		message.setUrl("");
		Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
		data.put("first", new WxTempleteMessage.ValueColor("测试消息推送标题", "#000000"));
		data.put("OrderID", new WxTempleteMessage.ValueColor("xx54613215561", ""));
		data.put("PersonName", new WxTempleteMessage.ValueColor("bob", ""));
		data.put("CheckInDate", new WxTempleteMessage.ValueColor("12-01-01", ""));
		data.put("CheckOutDate", new WxTempleteMessage.ValueColor("12-01-05", ""));
		data.put("remark", new WxTempleteMessage.ValueColor("测试完毕!", "#0579a6"));
		message.setData(data);

		//		boolean result = wxService.sendTempleteMessage(message);
		boolean result = wxApiService.sendTempleteMessage(message);
		if (!result) {
			smartResult.setState(StatusMsg.StatusMsg_103.getState());
		}
		return smartResult;
	}

	/**
	 小程序登录，检查处理微信的个人信息

	 @param rawOpenEntity 从微信后台获取到的openid 和 session_key原始数据
	 @return
	 */
	public WxLoginDto handleUserInfo(WxOpenid rawOpenEntity) {
		WxLoginDto wxLoginDto = null;
		Maker makerEntity = null;
		String openid = rawOpenEntity.getOpenid();
		WxOpenid wxOpenid = new WxOpenid().selectOne(Condition.create().eq("openid", openid).eq("app_type", 1));
		if (wxOpenid == null) {
			//没有用户信息，新建一个用户
			makerEntity = new Maker();
			makerEntity.insert();
			wxOpenid = new WxOpenid();
			wxOpenid.setOpenid(openid);
			wxOpenid.setSessionKey(rawOpenEntity.getSessionKey());
			wxOpenid.insert();
		} else {
			//存在用户，更新sessionkey
			makerEntity = new Maker().selectById(wxOpenid.getId());
			wxOpenid.setSessionKey(rawOpenEntity.getSessionKey());
			wxOpenid.update(Condition.create().eq("userid", makerEntity.getUserid()));
		}
		//int level = userEntity.getLevel();
		wxLoginDto = new WxLoginDto();
		wxLoginDto.setSession_key(wxOpenid.getSessionKey());
		wxLoginDto.setUnionid(wxOpenid.getUnionid());
		wxLoginDto.setOpenid(openid);
		wxLoginDto.setUserid(makerEntity.getUserid());
		return wxLoginDto;
	}

	/**
	 刷新微信NormalAccessToken
	 */
	public SmartResult refreshAccessToken() {
		WxNormalAccessToken normalAccessToken = wxApiService.getNormalAccessToken();
		SmartResult smartResult = new SmartResult();
		smartResult.setObject(normalAccessToken);
		return smartResult;
	}

	public SmartResult getWxUserState(BaseSimpleFormBean<String> formBean) {
		SmartResult smartResult = new SmartResult();
		if (formBean == null || StringUtil.isEmpty(formBean.getReqdata())) {
			LogUtil.error("获取用户状态-没有参数");
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		String reqdata = formBean.getReqdata();
		WxAuthorizeAccessToken authorizeAccessToken;

		if(UserType.TAXER == formBean.getIdtype()){
			authorizeAccessToken = wxApiService.getAuthorizeAccessToken(reqdata, wxTaxerConfig.getAppid(), wxTaxerConfig.getSecret());
		}else {
			authorizeAccessToken = wxApiService.getAuthorizeAccessToken(reqdata);
		}

		if (authorizeAccessToken == null) {
			LogUtil.error("获取用户状态-获取token失败");
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		String openid = authorizeAccessToken.getOpenid();
		String accessToken = authorizeAccessToken.getAccess_token();

		if (StringUtil.isEmpty(openid) || StringUtil.isEmpty(accessToken)) {
			LogUtil.error("获取用户状态-用户信息失败");
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		WxUserInfo wxUserInfo;
		if (UserType.MAKER == formBean.getIdtype() || UserType.MAKER_CROWDSOURCE == formBean.getIdtype()) {
			wxUserInfo = getWxUserInfo(1, openid, accessToken);
		} else if (UserType.COMPANY == formBean.getIdtype()) {
			wxUserInfo = getWxUserInfo(1, openid, accessToken);
		} else if (UserType.PARTNER == formBean.getIdtype()) {
			wxUserInfo = getWxUserInfo(1, openid, accessToken, wxPartnerConfig.getAppid(),
					wxPartnerConfig.getSecret());
		} else if (UserType.CROWDSOURCE == formBean.getIdtype()) {
			wxUserInfo = getWxUserInfo(1, openid, accessToken, wxCrowdsourceConfig.getAppid(),
					wxCrowdsourceConfig.getSecret());
		} else if (UserType.TAXER == formBean.getIdtype()) {
			wxUserInfo = getWxUserInfo(1, openid, accessToken);
		} else {
            wxUserInfo = getWxUserInfo(1, openid, accessToken);
		}

		WxUserStateDto wxUserStateDto = new WxUserStateDto().setOpenid(openid);
		if (null != wxUserInfo) {
			LogUtil.info("获取用户状态-用户信息：" + wxUserInfo.toString());
			wxUserStateDto.setAvatar(wxUserInfo.getHeadimgurl()).setNickname(wxUserInfo.getNickname());
		}
		smartResult.setObject(wxUserStateDto);

		//查看是否存在创客
		Maker maker =null;
		if(UserType.TAXER == formBean.getIdtype()){
			maker = makerMapper.getUserByTaxerOpenid(openid);
		}else {
			maker = makerMapper.getUserByOpenid(openid);
		}
		if (maker != null) {
			MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
			if (account != null) {
				wxUserStateDto.setUserid(maker.getUserid()).setIdtype(UserType.MAKER).setState(account.getRealnameAuth());
				return smartResult;
			}
		}

		//查看是否存在企业
		Company company = companyMapper.getCompanyByOpenid(openid);
		if (company != null) {
			wxUserStateDto.setUserid(company.getCompid()).setIdtype(UserType.COMPANY).setState(company.getState());
			return smartResult;
		}

		//都没有，返回空
		return smartResult;
	}
}
